package de.mafr.jsystest;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;


/**
 * Configuration for JSystest.
 * 
 * Typically, the configuration is read from a file called
 * <code>jsystest.properties</code> that is placed on the class path.
 */
public class SystemTestConfig {
	private static final String CONFIG_FILENAME = "jsystest.properties";
	
	private Properties config;
	
	public SystemTestConfig(Properties config) {
		this.config = config;
	}
	
	private SystemTestConfig() {
		this.config = loadProperties(getClassPathResource(CONFIG_FILENAME));
	}
	
	public static SystemTestConfig createFromClasspathProperties() {
		return new SystemTestConfig();
	}
	
	
	private InputStream getClassPathResource(String resourceName) {
		InputStream in = this.getClass().getClassLoader().getResourceAsStream(resourceName);
		
		if (in == null)
			throw new SystemTestException("classpath resource " + resourceName + " not found");

		return in;
	}
	
	private Properties loadProperties(InputStream in) {
		Properties result = new Properties();

		try {
			result.load(in);
		} catch (IOException e) {
			throw new SystemTestException("cannot load configuration: " + e.getMessage(), e);
		}
		
		return result;
	}
	
	/**
	 * Returns the property or throws an exception if there is none.
	 */
	public String getString(String key) {
		String value = config.getProperty(key);
		
		if (value == null)
			throw new SystemTestException("Property " + key + " is missing from config");

		return value;
	}

	/**
	 * Returns the property as an integer.
	 * 
	 * An exception is thrown if the property is missing or there is no valid integer.
	 */
	public int getInt(String key) {
		try {
			return Integer.parseInt(getString(key));
		} catch (NumberFormatException e) {
			throw new SystemTestException("Invalid integer for property " + key + ": " + getString(key));
		}
	}

	/**
	 * Return true iff the specified key is present in the config.
	 */
	public boolean hasKey(String key) {
		return config.getProperty(key) != null;
	}
}
